package LoginSystem;

import EncapsulatingObjects.User;
import TextDocument.UserAgreement;
import Util.Inspectionrules;
import Util.ShoppingCartUtil;
import Util.UiUtil;
import Util.UserDatabaseUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class RegisterPage {
    JFrame jf;
    JLabel account;
    JLabel tel;
    JLabel password1;
    JLabel password2;
    JLabel name;
    JLabel gender;
    JLabel birthday;
    JLabel year;
    JLabel month;
    JLabel day;
    JLabel reset;

    JTextField taccount;
    JTextField ttel;
    JTextField tname;
    JComboBox tgender;
    JComboBox tyear;
    JComboBox tmonth;
    JComboBox tday;

    JPasswordField tpass1;
    JPasswordField tpass2;

    JLabel login;
    JButton register;

    JRadioButton agreement;
    JLabel agreeText;

    User user = new User();
    UserDatabaseUtil ud = new UserDatabaseUtil();
    UiUtil ui = new UiUtil();

    RegisterPage() {
        init();
        ui.setFrameCenter(jf);
        ui.setFrameImage(jf);
        ui.setLogo(jf);
    }

    private void init() {
        jf = new JFrame("Register");
        jf.setLayout(null);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        account = new JLabel("Account");
        tel = new JLabel("Phone");
        password1 = new JLabel("Password");
        password2 = new JLabel("Password");
        reset = new JLabel("RESET");
        reset.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                resetInput();
            }
        });

        taccount = new JTextField(20);
        taccount.setToolTipText("The account number is 6-10 digit array or letter");
        ttel = new JTextField(20);
        ttel.setToolTipText("Mobile phone number 11 is a number");
        tpass1 = new JPasswordField(20);
        tpass1.setToolTipText("The password is 6-18 and consists of numbers, letters or underscores");
        tpass2 = new JPasswordField(20);
        tpass2.setToolTipText("Please confirm your password");

        name = new JLabel("Name");
        birthday = new JLabel("Birthday");
        year = new JLabel("Year");
        month = new JLabel("Month");
        day = new JLabel("Day");
        gender = new JLabel("Gender");
        tname = new JTextField(20);
        tname.setToolTipText("Please enter your name.");
        tgender = new JComboBox(new String[]{"Male", "Female"});
        tyear = new JComboBox();
        tmonth = new JComboBox();
        tday = new JComboBox();
        updateBirthday(tyear, tmonth);

        tyear.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                updataDay(jf, tyear, tmonth, tday);
            }
        });
        tmonth.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                updataDay(jf, tyear, tmonth, tday);
            }
        });

        login = new JLabel("LOGIN");
        register = new JButton("REGISTER");
        login.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        login.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                loginClicked();
            }
        });
        register.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        register.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                registerClicked();
            }
        });

        agreement = new JRadioButton("Agree");
        agreement.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        agreeText = new JLabel("User agreement");
        agreeText.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                new UserAgreement();
            }
        });
        agreeText.setForeground(Color.blue);
        agreeText.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        jf.add(agreement);
        jf.add(agreeText);

        jf.setSize(510, 485);
        account.setBounds(40, 50, 70, 20);
        tel.setBounds(40, 90, 70, 20);
        password1.setBounds(40, 130, 70, 20);
        password2.setBounds(40, 170, 70, 20);
        name.setBounds(40, 210, 70, 20);
        birthday.setBounds(40, 260, 70, 20);
        gender.setBounds(40, 290, 100, 50);

        taccount.setBounds(120, 50, 330, 30);
        ttel.setBounds(120, 90, 330, 30);
        tpass1.setBounds(120, 130, 330, 30);
        tpass2.setBounds(120, 170, 330, 30);
        tname.setBounds(120, 210, 330, 30);

        tyear.setBounds(120, 260, 60, 20);
        year.setBounds(190, 260, 40, 20);

        tmonth.setBounds(240, 260, 50, 20);
        month.setBounds(300, 260, 50, 20);

        day.setBounds(420, 260, 40, 20);
        tday.setBounds(360, 260, 50, 20);

        tgender.setBounds(120, 305, 80, 20);

        login.setBounds(40, 400, 80, 20);
        login.setForeground(Color.GRAY);

        register.setBounds(125, 345, 250, 50);
        reset.setBounds(400, 400, 80, 20);
        reset.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        reset.setForeground(Color.GRAY);

        agreement.setBounds(170,410,60,30);
        agreeText.setBounds(230,415,96,20);

        jf.add(account);
        jf.add(tel);
        jf.add(password1);
        jf.add(password2);
        jf.add(name);
        jf.add(birthday);
        jf.add(year);
        jf.add(month);
        jf.add(day);
        jf.add(gender);

        jf.add(taccount);
        jf.add(ttel);
        jf.add(tpass1);
        jf.add(tpass2);
        jf.add(tname);
        jf.add(tgender);
        jf.add(tmonth);
        jf.add(tyear);
        jf.add(tday);
        jf.add(login);
        jf.add(register);
        jf.add(reset);
        jf.setVisible(true);
    }

    private void resetInput() {
        taccount.setText("");
        ttel.setText("");
        tpass1.setText("");
        tpass2.setText("");
        tname.setText("");
        tyear.setSelectedIndex(40);
        tmonth.setSelectedIndex(0);
        updataDay(jf,tyear,tmonth,tday);
        tgender.setSelectedIndex(0);
    }

    private void loginClicked() {
        goLogin();
    }

    private void goLogin() {
        jf.dispose();
        LoginPage l = new LoginPage();
    }

    private void registerClicked() {
        if(!agreement.isSelected()){
            JOptionPane.showMessageDialog(jf,"Please agree to the user agreement first！");
            return;
        }
        try {
            user.setAccount(taccount.getText().trim());
            user.setName(tname.getText().trim());
            user.setPhone(ttel.getText().trim());
            user.setPassword(String.valueOf(tpass1.getPassword()).trim());
            String userPassword = String.valueOf(tpass2.getPassword()).trim();
            String birthdayDate = tyear.getSelectedItem().toString()
                    + "-" + String.format("%02d", tmonth.getSelectedItem())
                    + "-" + String.format("%02d", tday.getSelectedItem());

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            user.setBirthday(LocalDate.parse(birthdayDate, fmt));

            user.setGender(String.valueOf(tgender.getSelectedItem()));

            if (user.getAccount().equals("") || user.getName().equals("") || user.getPassword().equals("") || userPassword.equals("")) {
                JOptionPane.showMessageDialog(jf, "Please enter all information");
                return;
            }

            if (!user.getPassword().equals(userPassword)) {
                JOptionPane.showMessageDialog(jf, "The two passwords are inconsistent！");
                return;
            }

            if (!Inspectionrules.checkAccount(jf, user.getAccount()) || !Inspectionrules.checkPass(jf, user.getPassword()) || !Inspectionrules.checkTel(jf, user.getPhone())) {
                return;
            }

            Connection conn = ud.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from userdata");
            while (rs.next()) {
                if (user.getAccount().equals(rs.getString("account"))) {
                    JOptionPane.showMessageDialog(jf, "The account is already registered!");
                    return;
                }
            }
            ud.insertInfo(conn, user, false, false);
            addUser();
            if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(jf, "Register succeed！Do you want to login now?")) {
                goLogin();
            }
            stmt.close();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    private void updataDay(JFrame jf, JComboBox tyear, JComboBox tmonth, JComboBox tday) {
        int years = 1950;
        int months = 1;
        int days = 0;
        Object oYear = tyear.getSelectedItem();

        Object oMonth = tmonth.getSelectedItem();
        if (oYear == null || oMonth == null) {
            return;
        } else {
            years = (int) oYear;
            months = (int) oMonth;
        }

        switch (months) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                days = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                days = 30;
                break;
            case 2:
                if ((years % 4 == 0 && years % 100 != 0) || years % 400 == 0) {
                    days = 29;
                } else {
                    days = 28;
                }
                break;
        }
        tday.removeAllItems();
        for (int i = 1; i <= days; i++)
            tday.addItem(i);
    }

    void updateBirthday(JComboBox tyear, JComboBox tmonth) {
        int year = LocalDate.now().getYear();
        for (int i = 1950; i <= year; i++) {
            tyear.addItem(i);
        }
        tyear.setSelectedIndex(40);
        for (int i = 1; i <= 12; i++) {
            tmonth.addItem(i);
        }
        updataDay(jf, tyear, tmonth, tday);
    }

    void addUser() {
        ShoppingCartUtil su = new ShoppingCartUtil();
        ud.getUserId(user);
        su.addUser(user);
    }
}
